import numeral from 'numeral';
import dayjs from 'dayjs';

export type TimeDistance = 'day' | 'week' | 'month' | 'year'

export const isEmpty = (val: any): boolean => {
  return (
    (!val && val !== 0) ||
    (Array.isArray(val) && val.length === 0) ||
    (val !== null && typeof val === 'object' && !Object.keys(val).length)
  );
};

/**
 * 防抖
 * @param func 函数
 * @param delay 延迟
 */
export function debounce(func: Function, delay: number): Function {
  let timerId: ReturnType<typeof setTimeout>;
  return function (this: any): void {
    clearTimeout(timerId);
    timerId = setTimeout((): void => {
      func.apply(this, arguments);
    }, delay);
  };
}

/**
 * 防抖
 * @param func 函数
 * @param delay 延迟
 */
export function beforeDebounce(func: Function, delay: number): Function {
  let timerId: ReturnType<typeof setTimeout>;
  let isFirstTime: boolean = true;
  return function (this: any): void {
    clearTimeout(timerId);
    if (isFirstTime) {
      func.apply(this, arguments);
      isFirstTime = false;
    } else {
      timerId = setTimeout((): void => {
        func.apply(this, arguments);
      }, delay);
    }
  };
}

// 获取assets静态资源
export const getAssetsImage = (url: string): string => new URL(`../assets/images/${url}`, import.meta.url).href;

export const toYuan = (val: number): string => `¥${numeral(val).format('0,0')}`;

// 格式化为 K（千）的形式
export const toK = (number: number): string => numeral(number).format('0.0a');

/**
 * getTimeDistance(当前时间、本周、今月、今年)
 * @param type 'day' | 'week' | 'month' | 'year'
 * @returns {*[]}
 */
export function getTimeDistance(type: TimeDistance): dayjs.Dayjs[] {
  if (type === 'week') {
    return [dayjs().startOf('week').add(1, 'day'), dayjs().endOf('week').add(1, 'day'),];
  } else {
    return [dayjs().startOf(type), dayjs().endOf(type)];
  }
}

export const hasChild = (item: any): boolean => {
  return item.children && item.children.length !== 0;
};

/**
 * 两个路由对比
 * @param route1 路由1
 * @param route2 路由2
 * @returns {boolean}
 */
export const routeEqual = (route1: any, route2: any): boolean => {
  return route1.fullPath === route2.fullPath;
};

export const arrayToTree = function (arr: any) {
  const map: { [key: string]: any } = {};
  const root: any[] = [];
  arr.forEach((item: any) => {
    const data = {...item};
    if (map[item.id] && map[item.id].children) {
      data.children = map[item.id].children;
    }
    map[item.id] = data;
    if (item.parentId != null) {
      map[item.parentId] = map[item.parentId] || {children: []};
      map[item.parentId].children = map[item.parentId].children || [];
      map[item.parentId].children.push(map[item.id]);
    } else {
      root.push(map[item.id]);
    }
  });

  return root;
};

interface TreeHelperConfig {
  id: string;
  children: string;
  parentId: string;
}

// 默认配置
const DEFAULT_CONFIG: TreeHelperConfig = {
  id: 'id',
  children: 'children',
  parentId: 'parentId',
};

// 获取配置 Object.assign 从一个或多个源对象复制到目标对象
const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config);

export function listToTree<T = any>(list: any[], config: Partial<TreeHelperConfig> = {}): T[] {
  const conf = getConfig(config) as TreeHelperConfig;
  const nodeMap = new Map();
  const result: T[] = [];
  const {id, children, parentId} = conf;

  for (const node of list) {
    node[children] = node[children] || [];
    nodeMap.set(node[id], node);
  }
  for (const node of list) {
    const parent = nodeMap.get(node[parentId]);
    (parent ? parent[children] : result).push(node);
  }
  return result;
}

export function treeToList<T = any>(tree: any, config: Partial<TreeHelperConfig> = {}): T {
  config = getConfig(config);
  const {children} = config;
  const result: any = [...tree];
  for (let i = 0; i < result.length; i++) {
    if (!result[i][children!]) continue;
    result.splice(i + 1, 0, ...result[i][children!]);
  }
  return result;
}
/**
 * 将日期范围字符串转换为开始和结束时间戳
 * @param {string} dateRange - 格式为 "YYYY-MM-DD~YYYY-MM-DD"
 * @returns {Object} 包含开始和结束时间戳的对象；如果传入空字符串则两个值都为 undefined
 */
export function convertDateRangeToTimestamps(dateRange) {
  // 如果传入参数为空，返回包含两个 undefined 的对象
  if (!dateRange) {
    return {
      startTimestamp: undefined,
      endTimestamp: undefined
    };
  }

  const [startDateStr, endDateStr] = dateRange.split('~');

  // 转换为 Date 对象
  const startDate = new Date(startDateStr);
  const endDate = new Date(endDateStr);

  // 获取时间戳（秒）
  const startTimestamp = Math.floor(startDate.getTime() / 1000);
  const endTimestamp = Math.floor(endDate.getTime() / 1000);

  return {
    startTimestamp,
    endTimestamp
  };
}
